import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Card, Row, Col, Statistic, Button, Space, message, Spin, Tag, Descriptions } from 'antd';
import { ShoppingCartOutlined, HeartOutlined, ReloadOutlined } from '@ant-design/icons';
import api from '../services/api';
import dayjs from 'dayjs';

interface ProductDetail {
  id: number;
  code: string;
  name: string;
  category: {
    id: number;
    name: string;
    code: string;
  };
  product_type: string;
  risk_level: number;
  manager: string;
  company: string;
  establishment_date: string;
  management_fee: number;
  custody_fee: number;
  subscription_fee: number;
  redemption_fee: number;
  min_investment: number;
  max_investment?: number;
  liquidity_days: number;
  status: string;
  created_at: string;
  updated_at: string;
}

interface LatestPrice {
  net_value: number;
  accumulated_value: number;
  daily_return: number;
  price_date: string;
}

const ProductDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [product, setProduct] = useState<ProductDetail | null>(null);
  const [latestPrice, setLatestPrice] = useState<LatestPrice | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchProductDetail = async () => {
    if (!id) return;
    
    setLoading(true);
    try {
      // 获取产品详情
      const productResponse = await api.get(`/api/products/${id}/`);
      setProduct(productResponse.data);

      // 获取最新价格
      const priceResponse = await api.get(`/api/data-service/funds/${productResponse.data.code}/net-value/latest/`);
      setLatestPrice(priceResponse.data);
    } catch (error) {
      message.error('获取产品详情失败');
      console.error('Error fetching product detail:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleInvest = () => {
    message.info('投资功能开发中...');
  };

  const handleAddToWatchlist = () => {
    message.success('已添加到关注列表');
  };

  const handleRefresh = () => {
    fetchProductDetail();
  };

  const getProductTypeText = (type: string) => {
    const typeMap: { [key: string]: string } = {
      'stable': '稳健型',
      'balanced': '平衡型',
      'growth': '成长型',
      'aggressive': '进取型',
    };
    return typeMap[type] || type;
  };

  const getStatusColor = (status: string) => {
    const colorMap: { [key: string]: string } = {
      'active': 'green',
      'suspended': 'orange',
      'closed': 'red',
    };
    return colorMap[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const textMap: { [key: string]: string } = {
      'active': '正常',
      'suspended': '暂停',
      'closed': '关闭',
    };
    return textMap[status] || status;
  };

  const getRiskLevelColor = (level: number) => {
    if (level <= 2) return 'green';
    if (level <= 3) return 'orange';
    return 'red';
  };

  useEffect(() => {
    fetchProductDetail();
  }, [id]);

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!product) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <p>未找到产品信息</p>
      </div>
    );
  }

  const dailyReturn = latestPrice?.daily_return || 0;

  return (
    <div style={{ padding: '24px' }}>
      <Card 
        title={
          <div>
            <h2 style={{ margin: 0 }}>{product.name}</h2>
            <p style={{ margin: '4px 0 0 0', color: '#666' }}>代码: {product.code}</p>
          </div>
        }
        extra={
          <Space>
            <Button 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh}
              loading={loading}
            >
              刷新
            </Button>
            <Button 
              icon={<HeartOutlined />} 
              onClick={handleAddToWatchlist}
            >
              关注
            </Button>
            <Button 
              type="primary"
              icon={<ShoppingCartOutlined />} 
              onClick={handleInvest}
              disabled={product.status !== 'active'}
            >
              立即投资
            </Button>
          </Space>
        }
        style={{ marginBottom: '24px' }}
      >
        <Row gutter={[24, 16]}>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="单位净值"
              value={latestPrice?.net_value || 0}
              precision={4}
              valueStyle={{ 
                color: dailyReturn > 0 ? '#3f8600' : dailyReturn < 0 ? '#cf1322' : '#666',
                fontSize: '24px'
              }}
            />
            <p style={{ 
              color: dailyReturn > 0 ? '#3f8600' : dailyReturn < 0 ? '#cf1322' : '#666',
              margin: '4px 0 0 0'
            }}>
              {dailyReturn > 0 ? '+' : ''}{(dailyReturn * 100).toFixed(2)}%
            </p>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="累计净值"
              value={latestPrice?.accumulated_value || 0}
              precision={4}
            />
            <p style={{ margin: '4px 0 0 0', color: '#666' }}>
              {latestPrice?.price_date || '-'}
            </p>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="风险等级"
              value={product.risk_level}
              suffix="级"
            />
            <Tag color={getRiskLevelColor(product.risk_level)} style={{ marginTop: '4px' }}>
              {getProductTypeText(product.product_type)}
            </Tag>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="最小投资金额"
              value={product.min_investment}
              precision={2}
              prefix="¥"
            />
            <Tag color={getStatusColor(product.status)} style={{ marginTop: '4px' }}>
              {getStatusText(product.status)}
            </Tag>
          </Col>
        </Row>
      </Card>

      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="基本信息" style={{ height: '100%' }}>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="产品分类">
                {product.category.name}
              </Descriptions.Item>
              <Descriptions.Item label="基金经理">
                {product.manager}
              </Descriptions.Item>
              <Descriptions.Item label="基金公司">
                {product.company}
              </Descriptions.Item>
              <Descriptions.Item label="成立日期">
                {product.establishment_date}
              </Descriptions.Item>
              <Descriptions.Item label="赎回到账">
                {product.liquidity_days}个工作日
              </Descriptions.Item>
              {product.max_investment && (
                <Descriptions.Item label="最大投资金额">
                  ¥{product.max_investment ? product.max_investment.toLocaleString() : '0'}
                </Descriptions.Item>
              )}
            </Descriptions>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="费用信息" style={{ height: '100%' }}>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="管理费率">
                {(product.management_fee * 100).toFixed(2)}%
              </Descriptions.Item>
              <Descriptions.Item label="托管费率">
                {(product.custody_fee * 100).toFixed(2)}%
              </Descriptions.Item>
              <Descriptions.Item label="申购费率">
                {(product.subscription_fee * 100).toFixed(2)}%
              </Descriptions.Item>
              <Descriptions.Item label="赎回费率">
                {(product.redemption_fee * 100).toFixed(2)}%
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {dayjs(product.created_at).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {dayjs(product.updated_at).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ProductDetail;